import requests
import json

url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx4aa7c1c7ec1a905b&secret=eb7a39217bfe45c8552c0fa0cef03a6d"

res = requests.get(url=url)
jsonData = res.text

tokenRes = json.loads(jsonData)
access_token = tokenRes["access_token"]

AllInfo = {"totalNum": '', "dataTree": []}

## 文章总数
postUrl = "https://api.weixin.qq.com/tcb/databasequery?access_token=" + access_token
paras = {"env": "env-msg-3gk9rkuw7fcea3e0", "query": "db.collection('articles').doc('totalNum').get()"}

resTotalNum = requests.post(url=postUrl, json=paras)
totalNumStr = json.loads(resTotalNum.text)
totalNum = json.loads(totalNumStr["data"][0])["value"]
AllInfo["totalNum"] = totalNum
## 文章列表
postUrl = "https://api.weixin.qq.com/tcb/databasequery?access_token=" + access_token
data = {"env": "env-msg-3gk9rkuw7fcea3e0", "query": "db.collection('articles').doc('71bb51006110f14502ac6b60763c82a6').get()"}

res = requests.post(url=postUrl, json=data)
articleType = json.loads(res.text)
articleType = json.loads(articleType["data"][0])

dataTree = []

for type in articleType:
    typeTitle = type
    if type == "_id":
        continue
    typeJson = articleType[type]
    perTypeData = {'title': type, 'children': []}
    for perIssue in typeJson:
        issueTitle = perIssue
        ### 文章列表请求
        perPostName = typeJson[issueTitle]
        postUrl = "https://api.weixin.qq.com/tcb/databasequery?access_token=" + access_token
        data = {"env": "env-msg-3gk9rkuw7fcea3e0", "query": "db.collection('articles').doc('" + perPostName + "').get()"}
        res = requests.post(url=postUrl, json=data)
        articleList = json.loads(res.text)
        if len(articleList["data"]) == 0:
            continue
        articleList = json.loads(articleList["data"][0])
        treeLeaf = []
        for perArticle in articleList['list']:
            treeLeaf.append({'title': perArticle['title'], 'href': perArticle['url']})
        perTypeData['children'].append({'title': issueTitle, 'children': treeLeaf})
        ############

    dataTree.append(perTypeData)

AllInfo["dataTree"] = dataTree
#写出
f = open("./小程序/articleData.json", 'w', encoding='utf-8')
json.dump(AllInfo, f, ensure_ascii=False, indent=4)
print("res.text")